package com.dong.boot.service;

import com.dong.boot.mapper.HrMapper;
import com.dong.boot.mapper.HrRoleMapper;
import com.dong.boot.model.Hr;
import com.dong.boot.model.Role;
import com.dong.boot.utils.SystemConfigUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class HrService implements UserDetailsService {
    @Resource
    private HrMapper hrMapper;
    @Autowired
    private HrRoleMapper hrRoleMapper;
    @Override
    public Hr loadUserByUsername(String s) throws UsernameNotFoundException {
        Hr hr = hrMapper.loadUserByUsername(s);
        if (hr == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        List<Role> hrRolesById = hrMapper.getHrRolesById(hr.getId());
        hr.setRoles(hrRolesById);
        return hr;
    }

    public List<Hr> getAllHrs(String keyWords) {
        return hrMapper.getAllHrs(SystemConfigUtil.currentUser().getId(),keyWords);
    }

    public int updateHr(Hr hr) {
        return hrMapper.updateByPrimaryKey(hr);
    }

    @Transactional
    public boolean updateHrRole(Integer hrid, Integer[] rids) {
        hrRoleMapper.deleteByHrid(hrid);
        hrRoleMapper.addRole(hrid,rids);
        return true;
    }

    public boolean deleteHr(Integer id) {
        hrMapper.deleteByPrimaryKey(id);
        return true;
    }
}
